package com.guizi.halftimesroom;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.guizi.halftimesroom.frament.DailyFragment;
import com.guizi.halftimesroom.frament.DiscoverFragment;
import com.guizi.halftimesroom.frament.GroupFragment;
import com.guizi.halftimesroom.frament.MainPageFragment;
import com.guizi.halftimesroom.frament.MineFragment;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private List<Fragment> mfragmentList;
    private RadioGroup gr_title;
    private View fragment_contain;
    private int index,lastnumber;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        gr_title= (RadioGroup) findViewById(R.id.gr_title);
        fragment_contain=findViewById(R.id.fragment_contain);
        initFragment();

        RadioButton child_btn = (RadioButton) gr_title.getChildAt(index);
        child_btn.setChecked(true);
        showFragment(index,0);
        gr_title.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton rb_title = (RadioButton) group.findViewById(checkedId);
                index = group.indexOfChild(rb_title);
                showFragment(index,lastnumber);
                lastnumber=index;
            }
        });

    }

    private void showFragment(int showIndex, int hideIndex) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        Fragment showFragment = mfragmentList.get(showIndex);
        Fragment hideFragment = mfragmentList.get(hideIndex);
        if(!showFragment.isAdded()){
            ft.add(R.id.fragment_contain,showFragment);
        }
        if(showIndex==hideIndex){
            ft.show(showFragment).commit();
        }else {
            ft.show(showFragment).hide(hideFragment).commit();
        }
    }


    private void initFragment() {
        mfragmentList=new ArrayList<>();
        mfragmentList.add(new MainPageFragment());
        mfragmentList.add(new DiscoverFragment());
        mfragmentList.add(new DailyFragment());
        mfragmentList.add(new GroupFragment());
        mfragmentList.add(new MineFragment());
    }
}
